package com.it.xiaotao.io.echo;

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class BIOServer {
    private static class ClientThread implements Runnable {

        private Socket client = null;
        private Scanner scan = null;
        private PrintStream out = null;
        private boolean flag = true;

        public ClientThread(Socket client) throws Exception {
            this.client = client;
            this.scan = new Scanner(client.getInputStream());
            this.scan.useDelimiter("\n");
            this.out = new PrintStream(client.getOutputStream());
        }

        @Override
        public void run() {
            while (this.flag) {
                if (scan.hasNext()) {
                    String val = scan.next().trim();
                    if ("byebye".equalsIgnoreCase(val)) {
                        out.println("ByeByeBye...");
                        this.flag = false;
                    } else {
                        out.println("【ECHO】" + val);
                    }
                }
            }
            try {
                scan.close();
                out.close();
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws Exception {
        ServerSocket server = new ServerSocket(9999);
        System.out.println("等待客户端连接..........");
        boolean flag = true;
        while (flag) {
            Socket client = server.accept();
            new Thread(new ClientThread(client)).start();
        }
    }
}
